package com.codedancer.campus.manager.mq.consumer;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.manager.factory.SystemMessageFactory;
import com.codedancer.campus.manager.handler.SystemMessageHandler;
import com.codedancer.campus.manager.service.model.SystemMessageMqParamModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 系统消息消息队列（消费者）
 */
@Component
@Slf4j
public class SystemMessageMqListener {

    @Autowired
    private SystemMessageFactory systemMessageFactory;

    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "STARTCAMPUS.SYSTEMMESSAGE.QUEUE", declare = "true"),
        exchange = @Exchange(value = "STARTCAMPUS.EXCHANGE", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
        key = {"system.message"}
    ))
    @RabbitHandler
    public void saveSystemMessage(String param) {
        log.info("接受到的参数：{}", param);
        SystemMessageMqParamModel systemMessageMqParamModel = JSONUtil.toBean(param,
            SystemMessageMqParamModel.class);
        SystemMessageHandler systemMessageHandler = systemMessageFactory.getSystemMessageHandler(
            systemMessageMqParamModel.getMessageType().getValue());
        if (ObjectUtil.isEmpty(systemMessageHandler)) {
            log.info("没有对应的系统消息处理器");
            throw new BusinessException("没有对应的系统消息处理器");
        }
        systemMessageHandler.saveSystemMessage(systemMessageMqParamModel);
        log.info("系统消息消费成功");
    }
}
